//
//  UIImageView+Extensions.swift
//  status
//
//  Created by 彳亍 on 2017/3/22.
//  Copyright © 2017年 彳亍. All rights reserved.
//

import UIKit
import SDWebImage

// MARK: - SDWebImage
extension UIImageView {
    
    /// 设置网络图片
    ///
    /// - Parameters:
    ///   - URLString: 网络图片地址
    ///   - placeholder: 占位图片
    ///   - isClip: 是否剪裁
    ///   - backgroundColor: 背景颜色
    ///   - borderColor: 边缘颜色
    ///   - opaque: 不透明度
    func ch_setImage(URLString:String?, placeholder:UIImage?,isClip:Bool = false,backgroundColor:UIColor? = nil,borderColor:UIColor? = nil,opaque:Bool = false) {
        
        var placeholder = placeholder
        
        if isClip == true {
            placeholder = image?.ch_clipImage(size: self.bounds.size,
                                              backgroundColor: backgroundColor,
                                              borderColor: borderColor,
                                              opaque: opaque)
        }
        
        guard let URLString = URLString,let url = URL(string: URLString) else {
            
            image = placeholder
            
            return
        }
        
        
        
        // 加载网络图片
        sd_setImage(with: url, placeholderImage: placeholder, options: [], progress: nil) {[weak self] (image, _, _, _) in
            
            if isClip == true {
                self?.image = image?.ch_clipImage(size: self?.bounds.size,
                                                  backgroundColor: backgroundColor,
                                                  borderColor: borderColor,
                                                  opaque: opaque)
            }
        }
        
    }
    
}

// MARK: - UI
extension UIImageView {
    
    /// 便利构造器
    ///
    /// - Parameters:
    ///   - image: 图片
    ///   - mode: contentMode
    convenience init(image:UIImage?,mode:UIViewContentMode) {
        self.init(image:image)
        contentMode = mode
        
    }
    
    
}

// MARK: - 绘制
extension UIImageView {
    
    /// 绘制裁剪图片
    ///
    /// - Parameters:
    ///   - image: 图片
    ///   - size: 裁剪大小
    ///   - backgroundColor: 背景色
    ///   - borderColor: 边缘颜色
    ///   - opaque: 不透明度
    /// - Returns: UIImageView
    class func ch_draw(image:UIImage?,size:CGSize?,backgroundColor:UIColor?,borderColor:UIColor?,opaque:Bool)-> UIImageView {
        let image = image?.ch_clipImage(size:size , backgroundColor: backgroundColor, borderColor: borderColor, opaque: opaque)
        return UIImageView(image: image)
    }
    
}
